import IP from '../../static/ipconfig'
import router from '../router';
import axios from 'axios';
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import {getToken} from "../utils/auth";
import store from '@/store'

axios.defaults.timeout = 30000;  //超时时间
axios.defaults.withCredentials = true;  //允许跨域
//Content-Type 响应头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

axios.defaults.baseURL = "http://"+IP.IPCONFIG+":8888";


// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: "http://139.9.60.40:3030",
  // 超时
  timeout: 30000
})

//请求拦截器
axios.interceptors.request.use(config => {

  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  console.log("isToken:")
  console.log(isToken)

  if (getToken() && !isToken) {
    console.log("Authorization:")
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  // if (config.method === 'get' && config.params) {
  //   let url = config.url + '?' + tansParams(config.params);
  //   url = url.slice(0, -1);
  //   config.params = {};
  //   config.url = url;
  // }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

//响应拦截器
//响应拦截器
axios.interceptors.response.use(
  response => {
    const code = response.data.code
    console.log("---------------------------")
    console.log(response)
    // 二进制数据则直接返回
    if (response.request.responseType ===  'blob' || response.request.responseType ===  'arraybuffer') {
      return response.data
    }
    //如果reponse里面的status是200，说明访问到接口了，否则错误
    if(response.status == 200){
      if(code === 401){
        MessageBox.confirm('登录状态已过期，请重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
          store.commit('setLoginIn',false);
          store.commit('setIsActive',false);
          store.dispatch('LogOut').then(() => {
            location.href = '/';
          })})

      }
      return Promise.resolve(response);
    }else{
      return Promise.reject(response);
    }
  },
  error => {
    if(error.response.status){
      switch(error.response.status){
        case 401:       //未登录
          router.replace({
            path:'/',
            query:{
              redirect: router.currentRoute.fullPath
            }
          });
          break;
        case 404:   //没找到
          break;
      }
      return Promise.reject(error.response);
    }
  }
);

/**
 * 封装get方法
 */
export function get(url,params={}){
    return new Promise((resolve,reject) => {
        axios.get(url,{params:params})
        .then(response =>{
            resolve(response.data);
        })
        .catch(err =>{
            reject(err);
        })
    });
}

/**
 * 封装post方法
 */
export function post(url,data={},headers = {}){
    return new Promise((resolve,reject) => {
        axios.post(url,data,{ headers })
        .then(response =>{
            resolve(response.data);
        })
        .catch(err =>{
            reject(err);
        })
    });
}


export default service
